<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/10/19 11:20
 * Modified Time: 2019/10/19 11:20
 * Version: 2.0
 */

namespace App\Modules\Cashier\Services;


use App\Exceptions\AllValidatorException;
use App\Exceptions\DbException;
use App\Lib\CreateStaticNumber;
use App\Lib\Facades\FLAuth;
use App\Lib\Utilities;
use App\Models\GoodsOrderItem;
use App\Modules\Cashier\Criterias\GetStoreBillCriteria;
use App\Modules\Cashier\Repositories\BillRepository;
use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\Employee\Repositories\EmployeeRoyaltyRepository;
use App\Modules\Inventory\Repositories\GoodsOrderItemsRepository;
use App\Modules\Inventory\Repositories\GoodsOrderRepository;
use App\Modules\Inventory\Repositories\GoodsRepository;
use App\Modules\Inventory\Repositories\GoodsStockRepository;
use App\Modules\MemberCard\Repositores\CardTypeRepository;
use App\Modules\MemberCard\Repositores\MemberCardOrderRepository;
use App\Modules\MemberCard\Repositores\MemberCardRepository;
use App\Modules\Order\Repositories\AppointmentRepository;
use App\Modules\Order\Repositories\OrderItemRepository;
use App\Modules\Order\Repositories\OrderRepository;
use App\Modules\Order\Services\HaircutPriceService;
use App\Modules\Service\Repositories\ServiceRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use function foo\func;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CashierService extends BaseService
{
	use HaircutPriceService;
	protected $billRepository;
	protected $orderRepository;
	protected $serviceRepository;
	protected $cardTypeRepository;
	protected $memberCardRepository;
	protected $goodsRepository;
	protected $goodsOrderRepository;
	protected $goodsStockRepository;
	protected $appointmentRepository;
	protected $memberCardOrderRepository;
	protected $orderItemRepository;
	protected $employeeRoyaltyRepository;
	protected $employeeRepository;
	protected $goodsOrderItemsRepository;

	public function __construct(BillRepository $billRepository, OrderRepository $orderRepository, ServiceRepository $serviceRepository, CardTypeRepository $cardTypeRepository, MemberCardRepository $memberCardRepository, GoodsRepository $goodsRepository, GoodsOrderRepository $goodsOrderRepository, GoodsStockRepository $goodsStockRepository, AppointmentRepository $appointmentRepository, MemberCardOrderRepository $memberCardOrderRepository, OrderItemRepository $orderItemRepository, EmployeeRoyaltyRepository $employeeRoyaltyRepository,EmployeeRepository $employeeRepository,GoodsOrderItemsRepository $goodsOrderItemsRepository)
	{
		$this->billRepository = $billRepository;
		$this->orderRepository = $orderRepository;
		$this->serviceRepository = $serviceRepository;
		$this->cardTypeRepository = $cardTypeRepository;
		$this->memberCardRepository = $memberCardRepository;
		$this->goodsRepository = $goodsRepository;
		$this->goodsOrderRepository = $goodsOrderRepository;
		$this->goodsStockRepository = $goodsStockRepository;
		$this->appointmentRepository = $appointmentRepository;
		$this->memberCardOrderRepository = $memberCardOrderRepository;
		$this->orderItemRepository = $orderItemRepository;
		$this->employeeRoyaltyRepository = $employeeRoyaltyRepository;
		$this->serviceRepository = $serviceRepository;
		$this->employeeRepository = $employeeRepository;
		$this->goodsOrderItemsRepository = $goodsOrderItemsRepository;
	}


	/**
	 * 店铺账单列表
	 * @param $store_id
	 * @param $category
	 * @param $pageSize
	 * @param $status
	 * @return array
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getStoreBill($store_id, $category, $pageSize, $status, $user_id, $keyword = Null)
	{
		return  $this
			->billRepository
			->pushCriteria(new GetStoreBillCriteria($store_id, $category, $status,$user_id))
			->paginate($pageSize, ['*']);
	}

	/**
	 * 多服务开单
	 * @param $store_id
	 * @param $user_id
	 * @param $appointment_id
	 * @param $serviceList
	 * @param $member_card_id
	 * @return mixed
	 * @throws DbException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function createServiceBill($store_id, $user_id, $appointment_id, $serviceList, $member_card_id)
	{
		$is_appoint = 0;
		$appointment_id = empty($appointment_id) ? 0 : $appointment_id;
		// 如果有预约id 重写预约记录
		if ($appointment_id) {
			$this->appointmentRepository->complete($appointment_id);
			$is_appoint = 1;
		}
		$order_no = CreateStaticNumber::makeNo('order');

		$serviceListInfo = $this->checkServiceSuitBarberList($serviceList,$store_id);

		$main_recommend = empty($serviceListInfo[0]['barber_id']) ? 0 : $serviceListInfo[0]['barber_id'];

		$assist_recommend = empty($serviceListInfo[0]['assistant_id']) ? 0 : $serviceListInfo[0]['assistant_id'];

		$totalPrice = $originPrice = 0;
		foreach ($serviceListInfo as $v){
			$totalPrice += $v['price'];
			$originPrice += $v['service']->price;
		}

		DB::beginTransaction();
		try {
			// 添加订单信息
			$payment = empty($member_card_id) ? 0 : config('constant.payment.member_card');
			$order = $this->orderRepository->addNewOrderInfo($order_no, $store_id, $user_id, $appointment_id, $originPrice, $totalPrice, time(), $is_appoint, 3, $payment, 0, $member_card_id, 1, 0, 0, '');
			// 写多服务orderItem
			$orderItemList = array_map(function ($v) use ($order) {
				return [
					'order_id'     => $order->id,
					'service_id'   => $v['service_id'],
					'service_name' => $v['service']->name,
					'price'        => $v['service']->price,
					'real_price'   => $v['price'],
					'count'        => empty($v['count']) ? 1 : $v['count'],
					'barber_id'    => $v['barber_id'],
					'assistant_id' => $v['assistant_id'],
					'is_appoint'   => $v['is_appoint'],
					'sex'          => isset($v['sex']) ? $v['sex'] : 1
				];

			}, $serviceListInfo);
			// 订单明细
			$this->orderItemRepository->insertAll($orderItemList);
			// 账单表
			$billId = $this->billRepository->createBill(config('constant.bill.category.order'), $order->id, $store_id, $totalPrice, 0, $totalPrice, 0, $user_id, 0,$main_recommend,$assist_recommend);
			DB::commit();
			return $billId;
		} catch (\Exception $e) {
			DB::rollBack();
			Log::error('服务开单异常:' . $e->getMessage() . $e->getLine() . $e->getCode());
			throw new DbException();
		}

	}





	/**
	 * 服务开单 单服务的方法
	 * @param $store_id
	 * @param $user_id
	 * @param $barber_id
	 * @param $assistant_id
	 * @param $service_id
	 * @param $is_appoint
	 * @param $appointment_id
	 * @param int $member_card_id
	 * @throws DbException
	 */
//    public function createServiceBill($store_id, $user_id, $barber_id, $assistant_id, $service_id, $is_appoint,$appointment_id,$member_card_id=0)
//    {
//        //如果有预约id 重写预约记录
//        if($appointment_id!==null){
//            $this->appointmentRepository->complete($appointment_id);
//        }
//        $order_no = CreateStaticNumber::makeNo('order');
//        $service_data = $this->serviceRepository->find($service_id);
//        $price = $service_data->price;
//        $category = $member_card_id?5:1;
//        $service = [
//            'id' => $service_id,
//            'name' => $service_data->name,
//            'price' => $price
//        ];
//        $requestData = [
//            'real_price' => null,
//            'count' => 1
//        ];
//        DB::beginTransaction();
//        try {
//            $order = $this->orderRepository->addNewOrderInfo($order_no, $store_id, $barber_id, null, $price, 0, time(), $is_appoint, 3, null, 0, $member_card_id, 1, 0, 0, '', $assistant_id);
//            $this->orderItemRepository->add($order->id, $service, $requestData);
//            $order_id = $order->id;
//            $this->billRepository->createBill($category, $order_id, $store_id, $price, null, null, 0, $user_id, 0);
//            return DB::commit();
//        } catch (\Exception $exception) {
//            DB::rollBack();
//            throw new DbException();
//        }
//
//    }

	/**
	 * 会员卡开单
	 * @param $store_id
	 * @param $barber_id
	 * @param $type_id
	 * @param $name
	 * @param $mobile
	 * @param $sex
	 * @param $main_recommend
	 * @param $assist_recommend
	 * @return mixed
	 * @throws AllValidatorException
	 */
	public function createMemberCardBill($store_id, $barber_id, $member_card_id,$price, $main_recommend, $assist_recommend)
	{
		//获取卡类
//		$card_type = $this->cardTypeRepository->find($type_id);
		$cardInfo = $this->memberCardRepository->isExisted($member_card_id);
		$cardType = $cardInfo->cardType;
//		if (!$card_type) {
//			throw new AllValidatorException(['msg' => '卡类不存在']);
//		} else {
//			if ($card_type->store_id != $store_id) {
//				throw new AllValidatorException(['msg' => '卡类不存在']);
//			}
//		}

//		$attribute = $card_type->category;
//		$count = 0;
//		$balance = 0;
//		$price = $card_type->price;
//		$num = CreateStaticNumber::makeNo('card');
		DB::beginTransaction();
//		$member_card = $this->memberCardRepository->createMemberCard($store_id, $type_id, $name, $mobile, $sex, $attribute, $count, $balance, 0, $barber_id, 0, $num, 4);
		$member_card_order = $this->memberCardOrderRepository->createMemberCardOrder($store_id, $member_card_id, 1, $cardType->price, $price, 1);
		$bill = $this->billRepository->createBill(2, $member_card_order->id, $store_id, $cardType->price, bcsub($cardType->price ,$price,2), $price, 0, $barber_id, 0, $main_recommend, $assist_recommend);
		DB::commit();
		return $bill;
	}


	/**
	 * 购物开单
	 * @param $store_id
	 * @param $barber_id
	 * @param $goods_id
	 * @param $count
	 * @param $main_recommend
	 * @param $assist_recommend
	 * @return mixed
	 * @throws AllValidatorException
	 */
	public function createGoodsBill($store_id, $barber_id, $goodsList)
	{
		$main_recommend = $assist_recommend = 0;
		DB::beginTransaction();
		$total_price = $origin_price = 0;
		foreach ($goodsList as &$v){
			$goods = $this->goodsRepository->find($v['goods_id']);
			if (!$goods) {
				throw new AllValidatorException(['msg' => '商品不存在']);
			}
			$origin_price += bcmul($goods->market_price , $v['count'],2);
			$total_price  += bcmul( $goods->buying_price , $v['count'],2);
			$v['goods_name'] = $goods->name;
			$v['market_price'] = $goods->market_price;
			$v['buying_price'] = $goods->buying_price;
			if(!empty($v['barber_id'])) {
				$this->employeeRepository->isExited($v['barber_id']);
				if(empty($main_recommend)){
					$main_recommend = $v['barber_id'];
				}
			}
			if(!empty($v['assistant_id']))
			{
				$this->employeeRepository->isExited($v['assistant_id']);
				if(empty($assist_recommend)){
					$assist_recommend = $v['assistant_id'];
				}
			}
		}
		unset($v);

		//创建商品订单
		$goods_order = $this->goodsOrderRepository->createGoodsOrder($store_id, $barber_id, 0, 0, 0, $total_price, $origin_price, null, null, null);

		$this->goodsOrderItemsRepository->addItem($goods_order->id,$goodsList);

		$billId = $this->billRepository->createBill(3, $goods_order->id, $store_id, $origin_price, 0, $total_price, 0, $barber_id, 0, $main_recommend, $assist_recommend);
		DB::commit();
		return $billId;
	}


	/**
	 * 会员卡充值
	 * @param $store_id
	 * @param $barber_id
	 * @param $member_card_id
	 * @param $main_recommend
	 * @param $assist_recommend
	 * @return mixed
	 * @throws AllValidatorException
	 */
	public function createMemberCardRechargeBill($store_id, $barber_id, $member_card_id, $main_recommend, $assist_recommend)
	{
		//获取会员卡
		$member_card = $this->memberCardRepository->find($member_card_id);
		if (!$member_card) {
			throw new AllValidatorException(['msg' => '会员卡不存在']);
		}
		//获取卡类
		$card_type = $this->cardTypeRepository->find($member_card->type_id);
		if (!$card_type) {
			throw new AllValidatorException(['msg' => '卡类不存在']);
		}
		DB::beginTransaction();
		$member_card_order = $this->memberCardOrderRepository->createMemberCardOrder($store_id, $member_card_id, 2, null, null, 1);
		$bill = $this->billRepository->createBill(2, $member_card_order->id, $store_id, $card_type->price, 0, $card_type->price, 0, $barber_id, 0, $main_recommend, $assist_recommend);
		DB::commit();
		return $bill;
	}


	/**
	 * 获取账单订单详情
	 * @param $billId
	 * @return array
	 * @throws \App\Exceptions\NotFoundException
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getBillOrderDetailInfo($billId){
		$billInfo = $this->billRepository->isExited($billId);
		$orderInfo = [];
		switch ($billInfo->category){
			case config('constant.bill.category.order'):
				$orderInfo = $this->orderRepository->getOrderDetailInfo($billInfo->order_id);
				break;
			case config('constant.bill.category.card'):
				$orderInfo = $this->memberCardOrderRepository->getOrderDetailInfo($billInfo->order_id);
				break;
			case config('constant.bill.category.goods'):
				$orderInfo = $this->goodsOrderRepository->getOrderDetailInfo($billInfo->order_id);
				break;
		}
		return compact('billInfo','orderInfo');
	}
}